/*
 * Copyright (C) 2009 the original author or authors
 *     
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *         
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *         
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kommando.ui;

import java.awt.Cursor;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.MouseEvent;

import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputAdapter;

/**
 * @author Peter De Bruycker
 *
 */
public class DraggableWindow {
    public static void install(final Window window) {
     // make frame draggable by clicking in its contentpane and dragging it
        MouseInputAdapter mouseInputHandler = new MouseInputAdapter() {
            private Point offset;

            @Override
            public void mousePressed(MouseEvent e) {
                offset = e.getPoint();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                window.setCursor(null);
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                if (!SwingUtilities.isLeftMouseButton(e)) {
                    return;
                }
                window.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));

                Point where = e.getPoint();
                where.translate(-offset.x, -offset.y);
                Point loc = window.getLocationOnScreen();
                loc.translate(where.x, where.y);
                window.setLocation(loc.x, loc.y);
            }
        };
        window.addMouseListener(mouseInputHandler);
        window.addMouseMotionListener(mouseInputHandler);
    }
}
